package com.example.friend.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.core.constants.JwtConstants;
import com.example.common.core.domain.ResultCode;
import com.example.common.core.domain.TableDataInfo;
import com.example.friend.domain.exam.Exam;
import com.example.friend.domain.exam.dto.ExamQueryDTO;
import com.example.friend.domain.user.User;
import com.example.friend.domain.user.UserExam;
import com.example.friend.mapper.exam.ExamMapper;
import com.example.friend.mapper.user.UserExamMapper;
import com.example.friend.service.IUserExamService;
import com.example.security.exception.ServiceException;
import com.example.security.service.TokenService;
import com.example.service.RedisService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
@Slf4j
public class UserExamServiceImpl implements IUserExamService {

    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private UserExamMapper userExamMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private RedisService redisService;

    @Override
    public int enter(String token, Long examId) {
        Exam exam = examMapper.selectById(examId);
        if (exam == null) {
            throw new ServiceException(ResultCode.NON_EXAM);
        }
        if (exam.getStartTime().isBefore(LocalDateTime.now())) {
            throw new ServiceException(ResultCode.STARTED_EXAM);
        }
        Claims claims = tokenService.getClaims(token, JwtConstants.LOGIN_USER_KEY);
        Long userId = tokenService.getUserId(claims);
        UserExam userExam = userExamMapper.selectOne(new LambdaQueryWrapper<UserExam>()
                .eq(UserExam::getExamId, examId)
                .eq(UserExam::getUserId, userId));
        if (userExam != null) {
            throw new ServiceException(ResultCode.USER_HAS_EXAM);
        }
        UserExam insert = new UserExam();
        insert.setExamId(examId);
        insert.setUserId(userId);
        int insertM = userExamMapper.insert(insert);
        redisService.leftPushForList(CacheConstants.USER_EXAM_LIST + userId, examId);
        return insertM;
    }

    @Override
    public TableDataInfo list(ExamQueryDTO examQueryDTO) {
        return null;
    }
}
